<template>
  <div class="login-container">
    <div class="header">LOGO</div>
    <div class="center">
      <div class="main">
        <div class="banner"></div>
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
        >
          <div class="title-container">
            <h3 class="title">账号登录</h3>
          </div>

          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="username"
              v-model="loginForm.username"
              clearable
              placeholder="账号"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>

          <el-tooltip
            v-model="capsTooltip"
            content="大写已打开"
            placement="right"
            manual
          >
            <el-form-item prop="password">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                clearable
                :type="passwordType"
                placeholder="密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>
          </el-tooltip>
          <el-form-item prop="captcha">
            <span class="svg-container">
              <svg-icon icon-class="captcha" />
            </span>
            <el-input
              ref="captcha"
              v-model="loginForm.captcha"
              clearable
              placeholder="验证码"
              name="captcha"
              type="text"
              tabindex="3"
              autocomplete="on"
            ></el-input>
            <div
              v-loading="isLoadingCaptcha"
              class="captcha"
              @click="getCaptcha"
            >
              <img :src="imgCode" />
            </div>
          </el-form-item>
          <el-form-item prop="checkbox" style="border: none">
            <el-checkbox
              v-model="loginForm.checkbox"
              name="checkbox"
              tabindex="4"
              autocomplete="on"
            >
              已阅读并同意
            </el-checkbox>
            <el-button type="text">《服务条款》</el-button>
          </el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            class="btn"
            @click.native.prevent="handleLogin"
          >
            登录
          </el-button>
          <div class="forget-pwd">
            <div>
              还没有账号？
              <el-button type="text">立即注册</el-button>
            </div>
            <el-button type="text">忘记密码？</el-button>
          </div>
        </el-form>
      </div>
    </div>
    <div class="footer">
      Copyright © 2019 - 2022 广东蜂动科技有限公司 版权所有 粤ICP备19069505号
    </div>
  </div>
</template>

<script>
import { GetCaptcha } from '@/api/user'
export default {
  name: 'Login',
  // components: { SocialSign },
  data() {
    const validateCheckbox = (rule, value, callback) => {
      if (!value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }

    return {
      isLoadingCaptcha: false,
      imgCode: '',
      loginForm: {
        username: '',
        password: '',
        captcha: '',
        checkbox: false,
      },
      loginRules: {
        username: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入账号',
            // validator: validateUsername
          },
        ],
        password: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入密码',
            // validator: validatePassword
          },
        ],
        captcha: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入验证码',
          },
        ],
        checkbox: [
          {
            required: true,
            trigger: 'change',
            message: '请阅读并勾选服务条款',
            validator: validateCheckbox,
          },
        ],
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true,
    },
  },
  created() {
    this.getCaptcha()
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    async getCaptcha() {
      if (this.isLoadingCaptcha) return
      this.isLoadingCaptcha = true

      try {
        const { code, data: { captcha }} = await GetCaptcha()
        if (+code === 1) {
          this.imgCode = captcha // 'data:image/png;base64,'
        }
        this.isLoadingCaptcha = false
      } catch (err) {
        // console.log(err)
        this.isLoadingCaptcha = false
      }
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z'
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          const { username: acc, password: pwd, captcha } = this.loginForm
          this.$store
            .dispatch('user/login', { acc, pwd, captcha })
            .then(() => {
              // this.$message.success('登录成功')
              this.$router.push({
                path: this.redirect || '/',
                query: this.otherQuery,
              })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  },
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #fff;
$light_gray: #333;
$cursor: #333;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    flex: 1;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(0, 0, 0, 0.15); //rgba(255, 255, 255, 0.1);
    background: #fff; //rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    color: #333;
  }
  .el-form-item__content {
    line-height: 32px !important;
    display: flex;
    align-items: center;
  }
}
</style>

<style lang="scss" scoped>
$bg: #f5f5f5; //#2d3a4b;
$dark_gray: #454545;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .header {
    height: 50px;
    line-height: 50px;
    padding: 0 80px;
    background: #fff;
  }
  .center {
    flex: 1;
    min-width: 1100px;
    min-height: 560px;
    display: flex;
    justify-content: center;
    align-items: center;
    .main {
      width: 1100px;
      height: 480px;
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 0 10px #ccc;
      background: #fff;
      display: flex;
      .banner {
        width: 670px;
        height: 480px;
        background: url(~@/assets/img/login_bg.jpg) no-repeat;
        background-size: cover;
        background-position: center center;
      }
    }
  }
  .footer {
    height: 50px;
    // line-height: 50px;
    text-align: center;
    font-size: 14px;
  }

  .login-form {
    position: relative;
    flex: 1;
    max-width: 100%;
    padding: 40px;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      // color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .captcha {
    min-width: 64px;
    height: 32px;
    margin-right: 8px;
    img {
      height: 100%;
    }
  }

  .btn {
    height: 40px;
    width: 100%;
    font-size: 16px;
  }
  .forget-pwd {
    margin-top: 8px;
    display: flex;
    justify-content: space-between;
    font-size: 14px;
  }

  .show-pwd {
    // position: absolute;
    // right: 10px;
    // top: 7px;
    margin-right: 8px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
